<?php

namespace app\common\services;

use Exception;

use think\helper\Arr;
use GuzzleHttp\Client;
use think\facade\Cache;

/**
 * 千帆
 */
class QianFan
{
    private static $config = [
        'app_id' => '',
        'app_key' => '',
        'app_secret' => '',
        'access_token' => '',
    ];

    /**
     * [__construct 构造函数]
     * @param [type] $config [传递相关配置]
     */
    public function __construct($config = NULL)
    {
        $my_config = [
            'app_id' => env('qianfan.app_id'),
            'app_key' => env('qianfan.app_key'),
            'app_secret' => env('qianfan.app_secret'),
        ];
        self::$config = array_merge(self::$config, $my_config);
        $config && self::$config = array_merge(self::$config, $config);
    }

    /**
     * [accessToken 获取 access_token]
     * @return [type] [description]
     */
    public static function accessToken(bool $refresh = false)
    {
        if ($refresh || !Cache::has('qianfan_access_token')) {
            $params = [
                'client_id' => self::$config['app_key'],
                'client_secret' => self::$config['app_secret'],
                'grant_type' => 'client_credentials'
            ];

            $client = new Client();
            $url = 'https://aip.baidubce.com/oauth/2.0/token?' . http_build_query($params);
            $response = $client->request('GET', $url);
            $status = $response->getStatusCode();
            $body = $response->getBody()->getContents();
            if ($status != 200) {
                throw new Exception("error");
            }
            $result = json_decode($body, true) ?? [];
            if (!is_array($result)) {
                throw new Exception("error");
            }
            if (!empty($result['errcode'])) {
                throw new Exception($result['errmsg'] ?? 'error');
            }
            Cache::set('qianfan_access_token', $result['access_token'], $result['expires_in'] - 200);
        }

        return Cache::get('qianfan_access_token');
    }

    // 获取access_token
    public static function getAccessToken()
    {
        if (empty(self::$config['access_token'])) {
            $access_token = self::accessToken();
        } else {
            $access_token = self::$config['access_token'];
        }
        return $access_token;
    }

    /**
     * ERNIE-Bot 4.0 对话Chat
     */
    public static function chat($params)
    {

        $access_token = self::getAccessToken();
        $client = new Client();
        $url = 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro?access_token=' . $access_token;
        $response = $client->request('POST', $url, ['json' => $params]);
        $status = $response->getStatusCode();
        $body = $response->getBody()->getContents();
        if ($status != 200) {
            throw new Exception("error");
        }
        $result = json_decode($body, true) ?? [];
        if (!is_array($result)) {
            throw new Exception("error");
        }
        if (!empty($result['error_code'])) {
            throw new Exception($result['error_msg'] ?? 'error');
        }
        return $result;
    }
}
